
import java.io.File;
import java.io.IOException;
import org.bytedeco.javacv.FrameRecorder;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v107.network.Network;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.*;
import java.util.List;
import java.util.concurrent.*;
import util.SomeUtil;

public class pinduoduo {
    //下载路径
    public static final String dirPath = "D:\\ChromeDown\\downloadimage";


    public static void main(String[] args) throws InterruptedException, IOException {
        //图片存放的地址路径
        String inImg = "D:\\ChromeDown\\downloadimage\\ocr.png";
        String outImg = "D:\\ChromeDown\\downloadimage\\妖神记\\";
        File in =new File(inImg);
        File out =new File(outImg);
        //图片识别
        OCRCmd.OCR(in, out,"chi_sim");

        Thread.sleep(2000);
    }


    public static void main2(String[] args) throws InterruptedException, FrameRecorder.Exception {
        //合成的MP4 存放的地址路径 这里的路径并不会自动创建,需要手动提前创建好,否则会报错
        String mp4SavePath = "D:\\ChromeDown\\downloadimage\\img.mp4";
        //图片存放的地址路径
        String img = "D:\\ChromeDown\\downloadimage\\新建文件夹\\";
        int width = 690;
        int height = 1022;
//        SomeUtil.editBatchFileName(dirPath,"",".jpg");
        SomeUtil.img2Mp4(mp4SavePath,img ,width, height,1,"image",".png");
        Thread.sleep(2000);
    }

    public static void main1(String[] args) throws InterruptedException {
        int threadNum = 20;
        //需要下载的图片路径
        List<String> imageUrls = new LinkedList<String>();
        //图片类型
        List<String> imageTYpe = SomeUtil.imageType();
        //线程池
        ExecutorService executorService = new ThreadPoolExecutor(0, threadNum, 20L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(500));
        //设置驱动参数信息
        WebDriver webDriver = new ChromeDriver(chromeOptions());
        //设置devTools
        webDriver = devToolsOperation(webDriver, imageTYpe, imageUrls);
        webDriver.get("https://tool.liumingye.cn/music/?page=searchPage#/search/M/song/%E4%B8%96%E7%95%8C%E6%9D%AF%E4%B8%BB%E9%A2%98%E6%9B%B2");
        //显式等待
        WebDriverWait wait = new WebDriverWait(webDriver, Duration.ofSeconds(10), Duration.ofSeconds(3));
        //机器人滚动
        System.out.println("================开启机器人==================");
        SomeUtil.robotMouseWheel(9000L, webDriver, 4, 1000L);
        System.out.println("================关闭机器人==================");
        //下载图片
        System.out.println("================开始下载图片==================");
        SomeUtil.processSync(executorService, imageUrls);
        System.out.println("================完成下载图片==================");
        Thread.sleep(2000);
        webDriver.close();
    }

    /**
     * 设置devTools
     * @param webDriver
     * @param imageTYpe
     * @param imageUrls
     * @return
     */
    public static WebDriver devToolsOperation(WebDriver webDriver, List<String> imageTYpe, List<String> imageUrls) {
        webDriver = new Augmenter().augment(webDriver);
        DevTools devTools = ((HasDevTools) webDriver).getDevTools();
        devTools.createSession();
        devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
        // 获取Request信息
        devTools.addListener(Network.requestWillBeSent(), res -> {
            if (imageTYpe.contains(res.getRequest().getHeaders().get("Sec-Fetch-Dest"))) {
                System.out.println("requestWillBeSent: " + res.getRequest().getUrl());
            }
        });
        // 获取Response信息
        devTools.addListener(Network.responseReceived(), res -> {
            if (imageTYpe.contains(res.getResponse().getHeaders().get("content-type")) || imageTYpe.contains(res.getResponse().getMimeType())) {
                imageUrls.add(res.getResponse().getUrl());
                System.out.println("url: " + res.getResponse().getUrl());
            }
        });

        // 获取Response响应内容
//        devTools.addListener(Network.responseReceived(), res -> {
//            // 获取network 请求的responseBody
//            String responseBody = devTools.send(Network.getResponseBody(res.getRequestId())).getBody();
//            System.out.println("responseReceived: "+res.getResponse().getUrl());
//        });

        //窗口最大化
        webDriver.manage().window().maximize();
        return webDriver;
    }

    /**
     * 设置驱动参数信息
     *
     * @return
     */
    public static ChromeOptions chromeOptions() {
        // 设置webdirver路径  这个BrushTicket是指的这个代码所在的类。
        System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver2.exe");
        // 创建ChromeOptions，options可以设置一些网页请求头啥的
        ChromeOptions options = new ChromeOptions();
        // 指定本机chrome安装位置
        options.setBinary("C:\\Users\\User\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
        // 无浏览器模式
        //        options.addArguments("--headless");
        // 为了让root用户也能执行
        options.addArguments("--no-sandbox");
        // 设置屏蔽
        options.addArguments("--disable-blink-features=AutomationControlled");
        // 最大化运行（全屏窗口）,不设置，取元素会报错
        options.addArguments("'--start-maximized");
        //传下面参数来禁止掉谷歌受自动化控制的信息栏
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        //设置为 headless 模式避免报错用的参数
        //        options.addArguments("--disable-gpu");
        //文档地址:https://www.selenium.dev/zh-cn/documentation/webdriver/capabilities/shared/#unhandledpromptbehavior
        options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
        return options;
    }

}
